<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入奖品名称" v-model="listQuery.awardName">
      </el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <!-- <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button> -->
    </div>

    <div style="margin-bottom: 10px"></div>
    <div :v-show="allStatistical">
      <el-tag type="success"> 今日奖池总价值： {{this.allStatistical.todayAwardPrice}} 积分</el-tag>
      <el-tag type="success">今日用户抽奖积分总额：{{this.allStatistical.todayUse}} 积分</el-tag>
      <el-tag type="success">近3天积分消耗：{{this.allStatistical.threeDaysUse}} 积分</el-tag>
      <el-tag type="warning">今日奖池比例： {{this.allStatistical.percent}} </el-tag>
    </div>
    <div style="margin-bottom: 10px"></div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="奖品名称" prop="awardName">
      </el-table-column>

      <el-table-column align="center" property="url" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.url" width="80" />
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="中奖名单" prop="">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showRepetory(scope.row.id)">查看</el-button>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="抽奖计划" prop="">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showPlan(scope.row.id)">查看</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="积分价值" prop="price">
      </el-table-column>

      <!-- <el-table-column align="center" label="计划数量" prop="planNum">
      </el-table-column>

      <el-table-column align="center" label="已中奖数量" prop="awardNum">
      </el-table-column>

      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isOnSale ? 'success' : 'error' ">{{scope.row.status ? '未售' : '在售'}}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="primary" size="small" @click="lotteryPlan(scope.row)">抽奖计划设置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 中奖名单 -->
    <el-dialog title="中奖详情" width="800" :visible.sync="productVisible">
      <el-form :data="userForm" label-position="left">
        <el-form-item>
          <el-table size="small" :data="userForm" border fit highlight-current-row>
            <!-- <el-table-column align="center" label="用户昵称" prop="specifications" /> -->
            <el-table-column align="center" label="用户ID" prop="userId" />
            <el-table-column align="center" label="抽中时间" prop="drawTime" />
            <!-- <el-table-column align="center" label="最大数量" prop="bigNumber" /> -->
          </el-table>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 奖品计划 -->
    <el-dialog title="奖品上架安排" :visible.sync="planFormVisible">
      <el-form :rules="rulePlan" ref="planForm" :model="planForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="奖品名称" prop="awardName">
          <span v-text="planForm.awardName" style="color:#3cd94f;">
          </span>
        </el-form-item>

        <el-form-item label="单价(积分)" prop="integral">
          <span v-text="planForm.integral" style="color:#3cd94f;">
          </span>
        </el-form-item>

        <el-form-item label="奖品数量" prop="num">
          <el-input-number v-model="planForm.num" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="活动日期" prop="activeDate">
          <el-date-picker v-model="planForm.activeDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="planFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createPlan">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="奖品名称" prop="awardName">
          <el-input v-model="dataForm.awardName"></el-input>
        </el-form-item>

        <el-form-item label="图片" prop="url">
          <span style="color:gray;">(推荐像素：1440*800)</span>
          <el-upload class="avatar-uploader" :headers="headers" :action="uploadPath" list-type="picture-card" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif" :on-success="uploadPicUrl">
            <img v-if="dataForm.url" :src="dataForm.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="积分价值" prop="price">
          <el-input v-model="dataForm.price"></el-input>
        </el-form-item>

        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="false">在售</el-radio>
            <el-radio :label="true">未售</el-radio>
          </el-radio-group>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.el-dialog {
  width: 800px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { listAw, statistics, createAw, updateAw, queryUserDetails, createPlan } from '@/api/award'
import { uploadPath } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { getToken } from '@/utils/auth'

export default {
  name: 'Topic',
  components: { Editor },
  computed: {
    headers() {
      return {
        'X-Token': getToken()
      }
    }
  },
  data() {
    return {
      uploadPath,
      list: undefined,
      total: undefined,
      listLoading: true,
      userForm: [],
      listQuery: {
        page: 1,
        limit: 20
      },
      todayAwardIntegral: 0,
      allStatistical: {
        todayAwardPrice: 0,
        todayUse: 0,
        threeDaysUse: 0,
        percent: 0
      },
      planForm: {
        id: undefined,
        awardId: undefined,
        awardName: undefined,
        num: undefined,
        integral: undefined,
        activeDate: undefined
      },
      dataForm: {
        id: undefined,
        awardName: undefined,
        url: undefined,
        price: undefined,
        status: undefined
      },
      contentDetail: '',
      contentDialogVisible: false,
      productVisible: false,
      dialogFormVisible: false,
      planFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        awardName: [{ required: true, message: '奖品名称不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '商品价值不能为空', trigger: 'blur' }]
      },
      rulePlan: {
        num: [{ required: true, message: '奖品数量不能为空', trigger: 'blur' }],
        activeDate: [{ required: true, message: '活动时间不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getStatistics()
    this.getList()
  },
  methods: {
    getStatistics() {
      statistics().then(response => {
        this.allStatistical = response.data.data
      })
    },

    getList() {
      this.listLoading = true
      listAw(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
      this.getStatistics()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        awardName: undefined,
        url: undefined,
        num: undefined,
        awardNum: undefined,
        price: undefined,
        status: undefined
      }
    },

    createPlan() {
      this.$refs['planForm'].validate(valid => {
        if (valid) {
          this.planForm.awardId = this.planForm.id
          createPlan(this.planForm).then(response => {
            this.planFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadPicUrl: function(response) {
      this.dataForm.url = response.data.url
    },

    showRepetory(id) {
      queryUserDetails({ awardId: id }).then(response => {
        this.userForm = response.data.data
      })
      this.productVisible = true
    },

    showPlan(id) {
      this.$router.push({
        path: '/promotion/lottery/' + id + '/planlist'
      })
    },

    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createAw(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getStatistics()
          })
        }
      })
    },

    showContent(content) {
      this.contentDetail = content
      this.contentDialogVisible = true
    },

    lotteryPlan(row) {
      this.planForm = Object.assign({}, row)
      this.planForm.integral = row.price
      this.planFormVisible = true
      this.$nextTick(() => {
        this.$refs['planForm'].clearValidate()
      })
    },

    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateAw(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getStatistics()
          })
        }
      })
    }
  }
}
</script>
